package com.obrempon.credit.market.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.SeekBar
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonDialog
import com.obrempon.credit.market.databinding.ObremponApplyGuideDialogBinding
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.utils.ObremponTitleBarUtil
import org.json.JSONObject
import java.math.BigDecimal

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/13 15:41
 * @Annotation：申贷引导dialog
 */
class ObremponApplyGuideDialog: CommonDialog {
    private lateinit var binding: ObremponApplyGuideDialogBinding
    private var mCallback: IDialogCallback? = null

    //等待时长
    private var countdown = 5
    private var countdownTimer: MyCountDownTimer? = null

    constructor(context: Context) : super(context) {}
    constructor(context: Context, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    override fun initObremponWindow() {
        val params = window!!.attributes
        params.width = WindowManager.LayoutParams.MATCH_PARENT
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(R.style.dialog_scale_anim) //修改动画样式
        window!!.setGravity(Gravity.TOP)
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun takeObremponRootView(): View {
        binding = ObremponApplyGuideDialogBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initObremponView() {
        val top = ObremponTitleBarUtil.getStatusBarHeight()
        binding.applyGuideLayout.setPadding(0,top,0,0)
    }

    override fun initObremponListener() {
        setOnClickListener(binding.textGuideCountdown) //关闭
    }

    override fun takeObremponData() {
    }

    override fun onObremponViewClick(v: View?) {
        dismiss()
        if(mCallback != null){
            mCallback!!.onClick(v)
        }
    }

    /**
     * 设置额度值
     */
    fun showObremponApplyGuideData(data: JSONObject){
        //最小可选额度
        val minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        //最大值为剩余额度
        var maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString().toInt()
        //显示额度
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString().toInt()

        //颗粒度
        val scale = data.optInt("granularity")
        if (maxAmount <= minAmount){
            maxAmount = minAmount
        }

        //设置最大值
        val maxProcess = (maxAmount - minAmount) / scale
        binding.applyAmountSeekBar.max = maxProcess

        //设置当前值 为 三分之一
        val showAmount = maxProcess / 3
        binding.applyAmountSeekBar.progress = showAmount

//        val showAmount = (amount - minAmount) / scale
//        binding.applyAmountSeekBar.progress = showAmount
        // 当进度改变时调用
        val showProcess = showAmount * scale + minAmount
        binding.textAmount.text = "$showProcess"
        binding.textMinAmount.text = String.format(getString(R.string.obrempon_apply_choose_amount_min),minAmount)
        binding.textMaxAmount.text = String.format(getString(R.string.obrempon_apply_choose_amount_max),maxAmount)

        binding.applyAmountSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            @SuppressLint("SetTextI18n")
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 当进度改变时调用
                binding.textAmount.text = "${progress * scale + minAmount}"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 当用户开始触摸SeekBar（按下）时调用
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 当用户结束触摸SeekBar（抬手）时调用
            }
        })


        binding.textGuideCountdown.isEnabled = false
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    class MyCountDownTimer(private val dialog: ObremponApplyGuideDialog, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            dialog.countdown = (millisUntilFinished / 1000).toInt()
            dialog.showGuideTipsText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            dialog.showGuideCountDown()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showGuideTipsText(){
        binding.textGuideCountdown.text = "${countdown}s"
    }

    private fun showGuideCountDown(){
        binding.textGuideCountdown.isEnabled = true
        binding.textGuideCountdown.text = getString(R.string.obrempon_button_ok)
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.DIALOG.OBREMPON_DIALOG_APPLY_GUIDE_SHOW)
    }

    override fun dismiss() {
        super.dismiss()
        if (countdownTimer != null){
            countdownTimer = null
        }
        addEventPointRequestAction(ObremponEventPointType.DIALOG.OBREMPON_DIALOG_APPLY_GUIDE_DISMISS)
    }
}